<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// 后台通用方法
class Cx extends BaseController {

	public function __construct() {
        parent::__construct();

        // if(!isset($this->session->rmxUser['user_type']) || ($this->session->rmxUser['user_type'] != USER_TYPE_SCHOOL && $this->session->rmxUser['user_type'] != USER_TYPE_SUPER_ADMIN)) {
        //     show_error("抱歉，您没有权限访问");
        // }
    }

    // 单点登录
    public function sso() {
        $this->load->model('configModel');
        $this->load->model('schoolModel');
        $this->load->model('accountModel');
        $this->load->model('staffModel');
        $this->load->model('classesModel');
        $code = $this->get('code');
        $appId = $this->get('appId');
        $appKey = $this->get('appKey');
        $state = $this->get('state');
        $openid = $this->get('uid'); 

        $accessTokenUrl = 'https://auth.chaoxing.com/sns/oauth2/access_token/v1.0';
        $getUserUrl = 'http://v1.chaoxing.com/backSchool/user/getUserByTokenNew';

        // 判断数据库是否有access_token
        $accessTokenConfigJson = $this->configModel->get_config_info('cx_access_token', true);
        $expired = true;
        $accessTokenConfigArr = array();
        if($accessTokenConfigJson) {
            $accessTokenConfigArr = json_decode($accessTokenConfigJson, true);
            // 判断是否过期，过期时间前5分钟算过期
            if($accessTokenConfigArr && strtotime($accessTokenConfigArr['expires_time']) - 300 > time()) {
                // 未过期
                $expired = false;
            }
        }

        if($expired) {
            // 过期
            // 重新授权获取accessToken
            $accTokenParams = array(
                'appid' => $appId,
                'secret' => $appKey,
                'code' => $code,
                'grant_type' => 'authorization_code',
            );
            $queryArr = array();
            foreach($accTokenParams as $key => $value) {
                $str = $key . '=' . $value;
                array_push($queryArr, $str);
            }
            $str = implode('&', $queryArr);
            $accessTokenUrl = $accessTokenUrl . '?' . $str;
            $accTokenRes = $this->send_post($accessTokenUrl);
            $accTokenArr = json_decode($accTokenRes, true);
            if(empty($accTokenArr) || !isset($accTokenArr['access_token'])) {
                throw new Exception('服务错误，请联系管理员');
            }
            // 存入数据库sys_config
            $accessTokenConfigArr = array(
                'access_token' => $accTokenArr['access_token'],
                'expires_time' => $accTokenArr['expires_time']
            );
            $accessTokenConfigJson = json_encode($accessTokenConfigArr, JSON_UNESCAPED_UNICODE);
            $this->configModel->set_config_value('cx_access_token', $accessTokenConfigJson);
        }

        // 获取教师信息
        $getUserData = array(
            'access_token' => $accessTokenConfigArr['access_token'],
            'openid' => $openid,
            'expires_time' => $accessTokenConfigArr['expires_time'],
            'state' => $state,
        );
        $userDataRes = $this->send_post($getUserUrl, $getUserData);
        
        if(empty($userDataRes) ) {
            throw new Exception('服务错误，请联系管理员');
        }
        $userDataResArr = json_decode($userDataRes, true);
        if($userDataResArr['status'] == false || empty($userDataResArr['userInfo'])) {
            $msg = '服务错误，请联系管理员';
            if(isset($userDataResArr['msg'])) {
                $msg .= '：' . $userDataResArr['msg'];
            }
            throw new Exception($msg);
        }
        $userInfo = $userDataResArr['userInfo'];
        $xTeacherId = $userInfo['name'];

        // 获取超星同步学校
        $schoolInfo = $this->schoolModel->get_school_info_by_school_from(X_DATA_CHAOXING);
        // 获取教师数据库


        // 测试
        // $xTeacherId = '1054';

        $userInfo = $this->schoolModel->get_teacher_info_by_xid($schoolInfo['id'], $xTeacherId);
        // echo'<pre>';var_export($schoolInfo);exit;
        if(empty($userInfo)) {
            throw new Exception('服务错误，请联系管理员：用户id不存在');
        }
        // 自动登录
        // 获取校区
        $params['schoolId'] = $schoolInfo['id'];
        $params['isDelete'] = 0;
        $campusList = $this->schoolModel->get_campus_list($params);
        $campusInfo = $campusList[0];
        $menuIdSet = false;
        if($userInfo['user_type'] == USER_TYPE_SCHOOL) {
            $schoolMenuIdSet = $schoolInfo['school_module_set'];
            $menuIdSet = $schoolMenuIdSet;
        }

        if($userInfo['user_type'] == USER_TYPE_TEACHER) {
            $schoolMenuIdSet = $schoolInfo['school_module_set'];
            $userMenuIdSet = $this->staffModel->get_menu_id_by_role_id($userInfo['role_id_set']);
            $userMenuIdArr = explode(',', $userMenuIdSet);
            $schoolMenuIdArr = explode(',', $schoolMenuIdSet);
            // 获取菜单列表
            $menuList = $this->accountModel->get_admin_menu_all();
            // 按id
            $menuList = array_value_to_key($menuList, 'id');
            // 判断是否在学校权限里
            foreach($userMenuIdArr as $key => $id) {
                if(isset($menuList[$id])) {
                    $parentId = $menuList[$id]['menu_pid'];
                } else {
                    $parentId = -1;
                }
                if(!in_array($id, $schoolMenuIdArr) && !in_array($parentId, $schoolMenuIdArr)) {
                    unset($userMenuIdArr[$key]);
                }
            }
            $menuIdSet = implode(',', $userMenuIdArr);
        }
        // 根据用户类型，获取后台菜单列表
        $roleData = $this->accountModel->get_admin_menu($userInfo['user_type'], $menuIdSet);
        $userInfo['roleMenu'] = $roleData['roleMenu'];
        $userInfo['roleArray'] = $roleData['roleArray'];
        // 改成执教关系
        if($userInfo['user_type'] == USER_TYPE_TEACHER) {
            // 获取班级列表
            $classParams['isDelete'] = 0;
            $classParams['schoolId'] = $userInfo['school_id'];
            $classList = $this->classesModel->get_class_list($classParams);
            // 使用id作为键
            $classList = array_value_to_key($classList, 'id');
            // 获取执教关系列表
            $coachParams['teacherId'] = $userInfo['id'];
            $coachList = $this->staffModel->get_coach_list($coachParams);
            // 通过coachList获取任课班级
            $userInfo['classIdArr'] = $this->getTeacherClassByCoachList($coachList, $userInfo['school_id'])['teacherClassIdArr'];
            $userInfo['classArr'] = $this->getTeacherClassByCoachList($coachList, $userInfo['school_id'])['teacherClassArr'];
            // 学校管理员classArr数据太长，存储session报错Failed to decode session object. Session has been destroyed
            // 将学校管理员的user_type设置为2，即为后台管理员
            if($this->checkIsSchoolAdminByCoachList($coachList)) {
                $userInfo['user_type'] = USER_TYPE_SCHOOL;
                $userInfo['classArr'] = array();
            }
            $userInfo['class_ids'] = count($userInfo['classIdArr']) > 0 ? implode(',', $userInfo['classIdArr']) : '-1';
        }
         // 头像
         if($userInfo['user_type'] == USER_TYPE_SUPER_ADMIN) {
            // 超管默认为男头像
            $userInfo['headimgurl'] = site_url(APPLICATION_FOLDER. "/views/") . ADMIN_DIR. "/" . "assets/images/man.jpg";
         } else {
            if(empty($userInfo['headimgurl'])) {
                if($userInfo['user_type'] == USER_TYPE_SCHOOL) {
                    // 管理员默认为男头像
                   $userInfo['headimgurl'] = site_url(APPLICATION_FOLDER. "/views/") . ADMIN_DIR. "/" . "assets/images/man.jpg";
                } else {
                   // 判断性别
                   if(isset($userInfo['gender']) && $userInfo['gender'] == '女') {
                       $userInfo['headimgurl'] = get_sys_img('woman.jpg');
                   } else {
                       $userInfo['headimgurl'] = site_url(APPLICATION_FOLDER. "/views/") . ADMIN_DIR. "/" . "assets/images/man.jpg";
                   }
                }
           }
         }
        // 去掉残存的单点登录module的session
        if($this->session->intensiveModule){
            $this->session->set_userdata("intensiveModule", NULL);
        }
        // 登录成功，数据写入session
        $userInfo['school'] = $schoolInfo;
        $this->session->set_userdata("rmxUser", $userInfo);
        $this->session->set_userdata("campusInfo", $campusInfo);
        $this->session->set_userdata("campusList", $campusList);
        $this->session->set_userdata("campusInfo", $campusInfo);
        // 跳转到后台首页
        $redirectUrl = admin_url("home");

        redirect($redirectUrl);
        // echo'<pre>';var_export($userData);
        // exit;
    }

    // 同步学校数据
    public function update_cx_school($schoolId) {
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('configModel');
        $this->load->model('staffModel');
        $schoolInfo = $this->schoolModel->get_school_info($schoolId);
        if($schoolInfo['school_from'] != X_DATA_CHAOXING) throw new Exception("该学校不是来自系统，数据同步失败");

        // 请求接口
        include_once(APPPATH. "libraries/Chaoxing.php");
        $this->chaoxing = new Chaoxing($schoolInfo['school_x_id']);
        // echo '<pre>';var_export($apiDataArr);exit;

        // 初始化教师角色数据：任课教师，班主任，年级管理员，学校管理员
        $this->_update_cx_teacher_role_data($schoolId);
        // 同步年级数据接口
        $this->_update_cx_grade_data($schoolId);
        // 同步课室数据接口
        $this->_update_cx_classroom_data($schoolId);
        // 同步科目数据接口
        $this->_update_cx_subject_data($schoolId);
        // 同步班级数据接口
        $this->_update_cx_class_data($schoolId);
        // 同步学生数据接口
        $this->_update_cx_student_data($schoolId);
        // 同步教师数据接口
        $this->_update_cx_teacher_data($schoolId);
        // 把教师角色为空的设置‘任课教师’角色
        $this->_update_cx_coach_teacher_role_empty_data($schoolId);

        // 更新时间
        $update['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(SchoolModel::$schoolTable, $update, "id='{$schoolId}'");
        exit(json("同步数据成功", true));
    }

    // 初始化教师角色数据：任课教师，班主任，年级管理员，学校管理员
    private function _update_cx_teacher_role_data($schoolId) {
        // 获取学校角色数据
        $roleList = $this->staffModel->get_role_list($schoolId);
        // 将role_name作为键值
        $roleList = array_value_to_key_with_underline($roleList, 'role_name');
        $insertDataArr = array();
        if(!isset($roleList['任课教师'])) {
            $saveData['school_id'] = $schoolId;
            $saveData['role_name'] = '任课教师';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '0,89,90,91,92,94,104,106,107,108,109,110,111,112,113,114,118,119';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if(!isset($roleList['班主任'])) {
            $saveData['school_id'] = $schoolId;
            $saveData['role_name'] = '班主任';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '0,89,90,91,92,94,104,106,107,108,109,110,111,112,113,114,118,119';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if(!isset($roleList['年级管理员'])) {
            $saveData['school_id'] = $schoolId;
            $saveData['role_name'] = '年级管理员';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '0,89,90,91,92,94,104,106,107,108,109,110,111,112,113,114,118,119';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if(!isset($roleList['学校管理员'])) {
            $saveData['school_id'] = $schoolId;
            $saveData['role_name'] = '学校管理员';
            $saveData['role_parent_id'] = 0;
            $saveData['role_parent_tree'] = 0;
            $saveData['role_menu'] = '89,90,91,92,93,94,95,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,147,156';
            $saveData['is_delete'] = 0;
            $saveData['createtime'] = date("Y-m-d H:i:s");
            $saveData['updatetime'] = date("Y-m-d H:i:s");
            array_push($insertDataArr, $saveData);
        }
        if($insertDataArr) {
            // 插入
            $this->db->insert_batch(StaffModel::$roleTable, $insertDataArr);
        }
    }

    // 同步年级接口
    private function _update_cx_grade_data($schoolId) {
        $apiDataArr = $this->chaoxing->get_grade_list($schoolId);

        // echo '<pre>';var_export($apiDataArr);exit;

        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(ClassesModel::$gradeTable, $deleteState, "`school_id`='{$schoolId}'");
        // 获取本校全部年级
        $gradeParams['schoolId'] = $schoolId;
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeList = array_value_to_key($gradeList, 'x_grade_id');
        // 获取默认校区
        $campusParams['isDelete'] = 0;
        $campusParams['schoolId'] = $schoolId;
        $campusArr = $this->schoolModel->get_campus_list($campusParams);
        if($campusArr) {
            $defaultCampusId = $campusArr[0]['id'];
        } else {
            $defaultCampusId = 0;
        }

        //获取全部信息接口
        $insertGradeBatch = $updateGradeBatch = array();
        foreach($apiDataArr as $item) {
            if($item['gradeName']) {
                $xGradeId = $item['gradeId'];
                // 设置年级数组
                $gradeData['school_id'] = $schoolId;
                $gradeData['x_grade_id'] = $xGradeId;
                $gradeData['campus_id'] = $defaultCampusId;        // 设置校区id
                // 自己做一个唯一ID
                $gradeData['x_unique_id'] = $schoolId. "_". $defaultCampusId. "_". $xGradeId;
                $gradeData['grade_name'] = $item['gradeName'];
                $gradeData['year_of_admission'] = $item['entranceYear'];
                $gradeData['is_delete'] = 0;
                $gradeData['updatetime'] = date("Y-m-d H:i:s");
                if(isset($gradeList[$xGradeId])) {
                    $updateGradeBatch[$xGradeId] = $gradeData;
                } else {
                    $gradeData['createtime'] = $gradeData['updatetime'];
                    $insertGradeBatch[$xGradeId] = $gradeData;
                }
            }
        }
        if(count($insertGradeBatch)) $this->db->insert_batch(ClassesModel::$gradeTable, $insertGradeBatch);
        if(count($updateGradeBatch)) $this->db->update_batch(ClassesModel::$gradeTable, $updateGradeBatch, "x_unique_id");
        
    }

    // 同步课室接口
    private function _update_cx_classroom_data($schoolId) {
        $apiDataArr = $this->chaoxing->get_location_list($schoolId);

        // 不分校区
        // 将全部班级数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(ClassesModel::$classroomTable, $deleteState, "`school_id`='{$schoolId}'");
        // 获取默认校区
        $campusParams['isDelete'] = 0;
        $campusParams['schoolId'] = $schoolId;
        $campusArr = $this->schoolModel->get_campus_list($campusParams);
        if($campusArr) {
            $defaultCampusId = $campusArr[0]['id'];
        } else {
            $defaultCampusId = 0;
        }
        // 获取本校全部课室
        $roomParams['schoolId'] = $schoolId;
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'x_classroom_id');
        // 遍历接口所有数据
        $insertRoomBatch = $updateRoomBatch = array();
        foreach($apiDataArr as $item) {
            $xLocationId = $item['locationId'];

            $roomData['school_id'] = $schoolId;
            $roomData['x_classroom_id'] = $xLocationId;
            $roomData['campus_id'] = $defaultCampusId;             // 设置校区ID
            // 自己做一个唯一ID
            $roomData['x_unique_id'] = $schoolId. "_". $defaultCampusId. "_". $xLocationId;
            $roomData['classroom_name'] = $item['locationName'];
            $roomData['is_delete'] = 0;
            $roomData['updatetime'] = date("Y-m-d H:i:s");
            // 更新还是新增
            if(isset($roomList[$xLocationId])) {
                $updateRoomBatch[] = $roomData;
            } else {
                $roomData['createtime'] = $roomData['updatetime'];
                $insertRoomBatch[] = $roomData;
            }
            
        }
        if(count($insertRoomBatch)) $this->db->insert_batch(ClassesModel::$classroomTable, $insertRoomBatch);
        if(count($updateRoomBatch)) $this->db->update_batch(ClassesModel::$classroomTable, $updateRoomBatch, "x_unique_id");
           
    }

    // 同步科目接口
    private function _update_cx_subject_data($schoolId) {
        $apiDataArr = $this->chaoxing->get_subject_list($schoolId);

        // 不分校区
        // 将全部班级数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(SchoolModel::$schoolLessonTable, $deleteState, "`school_id`='{$schoolId}'");
    
        // 获取本校全部课室
        $subjectParams['schoolId'] = $schoolId;
        $subjectList = $this->schoolModel->get_lesson_list($subjectParams);
        $subjectList = array_value_to_key($subjectList, 'x_lesson_id');
        // 遍历接口所有数据
        $insertSubjectBatch = $updateSubjectBatch = array();
        foreach($apiDataArr as $item) {
            $xSubjectId = $item['lessonId'];

            $subjectData['school_id'] = $schoolId;
            $subjectData['x_lesson_id'] = $xSubjectId;
            // 自己做一个唯一ID
            $subjectData['x_unique_id'] = $schoolId. "_". $xSubjectId;
            $subjectData['lesson_name'] = $item['lessonName'];
            $subjectData['is_delete'] = 0;
            $subjectData['updatetime'] = date("Y-m-d H:i:s");
            // 更新还是新增
            if(isset($subjectList[$xSubjectId])) {
                $updateSubjectBatch[] = $subjectData;
            } else {
                $subjectData['createtime'] = $subjectData['updatetime'];
                $insertSubjectBatch[] = $subjectData;
            }
            
        }
        if(count($insertSubjectBatch)) $this->db->insert_batch(SchoolModel::$schoolLessonTable, $insertSubjectBatch);
        if(count($updateSubjectBatch)) $this->db->update_batch(SchoolModel::$schoolLessonTable, $updateSubjectBatch, "x_unique_id");
            
    }

    // 同步班级接口
    private function _update_cx_class_data($schoolId) {
        $apiDataArr = $this->chaoxing->get_class_list($schoolId);
        // echo '<pre>';var_export($apiDataArr);exit;

        // 不分校区
        // 将全部班级数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(ClassesModel::$classTable, $deleteState, "`school_id`='{$schoolId}'");
        // 获取默认校区
        $campusParams['isDelete'] = 0;
        $campusParams['schoolId'] = $schoolId;
        $campusArr = $this->schoolModel->get_campus_list($campusParams);
        if($campusArr) {
            $defaultCampusId = $campusArr[0]['id'];
        } else {
            $defaultCampusId = 0;
        }
        // 获取本校全部年级
        $gradeParams['schoolId'] = $schoolId;
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeList = array_value_to_key($gradeList, 'x_grade_id');
        // 获取本校全部班级
        $classParams['schoolId'] = $schoolId;
        $classList = $this->classesModel->get_class_list($classParams);
        // x_class_id可能以0未开头，导致错误，改用unique_id
        // $classList = array_value_to_key($classList, 'x_class_id');
        $classList = array_value_to_key($classList, 'x_unique_id');
        // echo '<pre>';var_export($classList);exit;
        // 获取本校全部课室
        $roomParams['schoolId'] = $schoolId;
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        // $roomList = array_value_to_key($roomList, 'x_classroom_id');
        // 通过locationName去获取
        $roomList = array_value_to_key($roomList, 'classroom_name');
        //获取全部行政班信息接口
        $insertClassBatch = $updateClassBatch = array();
        foreach($apiDataArr as $item) {
            if(isset($gradeList[$item['gradeId']])) {
                $classData['school_id'] = $schoolId;
                $classData['campus_id'] = $defaultCampusId; // 设置校区id
                $classData['grade_id'] = $gradeList[$item['gradeId']]['id'];
                $classData['x_class_id'] = $item['classId'];
                // 自己做一个唯一ID
                $classData['x_unique_id'] = $schoolId. "_". $defaultCampusId . "_". $item['classId'];
                // 通过locationName去获取
                // $classData['classroom_id'] = isset($roomList[$item['locationId']]) ? $roomList[$item['locationId']]['id'] : 0;
                $classData['classroom_id'] = isset($roomList[$item['locationName']]) ? $roomList[$item['locationName']]['id'] : 0;
                $classData['class_name'] = $item['className'];
                // 如果有班主任
                // $classData['class_master'] = (isset($item['classTeacher']) && $item['classTeacher'] && isset($item['classTeacher']['teacherEID']) && isset($teacherList[$item['classTeacher']['teacherEID']])) ? $teacherList[$item['classTeacher']['teacherEID']]['id'] : 0;
                
                if($item['classType'] == '行政班' || $item['classType'] == '') {
                    $classType = CLASSES_TYPE_NORMAL;
                } elseif($item['classType'] == '教学班') {
                    $classType = CLASSES_TYPE_TEACHING;
                } else {
                    $classType = CLASSES_TYPE_ELECTIVE;
                }
                $classData['class_type'] = $classType;
                $classData['is_delete'] = 0;
                $classData['updatetime'] = date("Y-m-d H:i:s");
                // if(isset($classList[$item['classId']])) {
                if(isset($classList[$classData['x_unique_id']])) {      
                    $updateClassBatch[] = $classData;
                } else {
                    $classData['createtime'] = $classData['updatetime'];
                    $insertClassBatch[] = $classData;
                }
            }
        }

        if(count($insertClassBatch)) $this->db->insert_batch(ClassesModel::$classTable, $insertClassBatch);
        if(count($updateClassBatch)) $this->db->update_batch(ClassesModel::$classTable, $updateClassBatch, "x_unique_id");
    }

    // 同步学生接口
    private function _update_cx_student_data($schoolId) {
        $apiDataArr = $this->chaoxing->get_student_list($schoolId);

        // 不分校区
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $deleteState['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(SchoolModel::$schoolStudentTable, $deleteState, "`school_id`='{$schoolId}'");
        
        // 获取本校全部学生
        $studentParams['schoolId'] = $schoolId;
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $studentList = array_value_to_key($studentList, 'x_student_id');
        // 获取行政班
        $classParams['schoolId'] = $schoolId;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'x_class_id');
        // 以班级名称作为键值
        $classListWithNameKey = array_value_to_key($classList, 'class_name');
        // 获取接口学生
        $insertStudentBatch = $updateStudentBatch = array();
        $defaultPwd = password_hash(123456, PASSWORD_DEFAULT);
        foreach($apiDataArr as $item) {
            if(isset($classList[$item['qualifiedClassID']])) {
                $studentData['is_delete'] = 0;
                $studentData['school_id'] = $schoolId;
                $studentData['campus_id'] = $classList[$item['qualifiedClassID']]['campus_id'];      // 设置校区ID
                $studentData['x_student_id'] = $item['studentId'];  // 对应人员唯一编号
                $studentData['username'] = $item['studentUserName'] ? $item['studentUserName'] : '';        // 对应学号
                $studentData['realname'] = $item['studentName'] ? $item['studentName'] : $item['studentUserName'];
                $studentData['realcard'] = '';
    
                // 自己做一个唯一ID
                $studentData['x_unique_id'] = $schoolId. "_". $classList[$item['qualifiedClassID']]['campus_id'] . "_". $item['studentId'];
    
                $studentData['class_id'] = $classList[$item['qualifiedClassID']]['id'];

                // 教学班
                if($item['teachingClassFullNames']) {
                    $nameArr = explode(',', $item['teachingClassFullNames']);
                    $classIdArr = array();
                    foreach($nameArr as $name) {
                        if(isset($classListWithNameKey[$name])) {
                            $classId = $classListWithNameKey[$name]['id'];
                            array_push($classIdArr, $classId);
                        }
                    }
                    $classIdStr = implode(',', $classIdArr);
                    $studentData['teaching_class_id'] = $classIdStr;
                } else {
                    $studentData['teaching_class_id'] = '';
                }
                
                $studentData['gender'] = trim($item['gender']) ? trim($item['gender']) : '男'; // 默认男
                if($item['headimgurl']) {
                    $headimgurl = $item['headimgurl'];
                } else {
                    $headimgurl = $studentData['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg');
                }
                $studentData['headimgurl'] = $headimgurl; // 默认男头像
                $studentData['mobile'] = '';
                $studentData['updatetime'] = date("Y-m-d H:i:s");
                if(isset($studentList[$item['studentId']])) {
                    $updateStudentBatch[] = $studentData;
                } else {
                    $studentData['password'] = $defaultPwd;
                    $studentData['createtime'] = $studentData['updatetime'];
                    $insertStudentBatch[] = $studentData;
                }
            }
        }
        if(count($insertStudentBatch)) $this->db->insert_batch(SchoolModel::$schoolStudentTable, $insertStudentBatch);
        if(count($updateStudentBatch)) $this->db->update_batch(SchoolModel::$schoolStudentTable, $updateStudentBatch, "x_unique_id");
    }

    // 同步教师接口
    private function _update_cx_teacher_data($schoolId) {
        $apiDataArr = $this->chaoxing->get_teacher_list($schoolId);

        // 不分校区
        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $deleteState['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(SchoolModel::$schoolUserTable, $deleteState, "`school_id`='{$schoolId}' AND `user_type`=" . USER_TYPE_TEACHER);
        
        // 获取本校全部教师
        $teacherParams['schoolId'] = $schoolId;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'x_teacher_id');

        // 获取接口教师
        $insertTeacherBatch = $updateTeacherBatch = array();
        $defaultPwd = password_hash(123456, PASSWORD_DEFAULT);
        foreach($apiDataArr as $item) {
            $teacherData['is_delete'] = 0;
            $teacherData['school_id'] = $schoolId;
            $teacherData['user_type'] = USER_TYPE_TEACHER;
            $teacherData['x_teacher_id'] = $item['teacherId'];  // 对应人员唯一编号
            $teacherData['username'] = $item['teacherUserName'] ? $item['teacherUserName'] : '';        // 对应学号
            $teacherData['realname'] = $item['teacherName'] ? $item['teacherName'] : $item['teacherUserName'];

            // 自己做一个唯一ID
            $teacherData['x_unique_id'] = $schoolId. "_". $item['teacherId'];
            
            $teacherData['gender'] = trim($item['gender']) ? trim($item['gender']) : '男'; // 默认男
            $headimgurl = $teacherData['gender'] == '男' ? site_url(APPLICATION_FOLDER. "/views/") . ADMIN_DIR. "/" . "assets/images/man.jpg" : get_sys_img('woman.jpg');
            $teacherData['headimgurl'] = $headimgurl; // 默认男头像
            $teacherData['mobile'] = $item['mobile'];
            $teacherData['updatetime'] = date("Y-m-d H:i:s");
            if(isset($teacherList[$item['teacherId']])) {
                $updateTeacherBatch[] = $teacherData;
            } else {
                $teacherData['password'] = $defaultPwd;
                $teacherData['createtime'] = $teacherData['updatetime'];
                $insertTeacherBatch[] = $teacherData;
            }
            
        }
        if(count($insertTeacherBatch)) $this->db->insert_batch(SchoolModel::$schoolUserTable, $insertTeacherBatch);
        if(count($updateTeacherBatch)) $this->db->update_batch(SchoolModel::$schoolUserTable, $updateTeacherBatch, "x_unique_id");
    }

    // 把教师角色为空的设置‘任课教师’角色
    private function _update_cx_coach_teacher_role_empty_data($schoolId) {
        // 获取教师角色-学校管理员
        $teacherRoleIdArr = $this->staffModel->get_role_id_by_name($schoolId, '任课教师');
        if(isset($teacherRoleIdArr['id'])) {
            $this->db->update(SchoolModel::$schoolUserTable, array('role_id_set'=> $teacherRoleIdArr['id']), "role_id_set='' AND `user_type`=" . USER_TYPE_TEACHER);
        }
    }

    // 同步课表接口
    private function _update_hzy_schedule_data($schoolId){
        // 本周课程表
        $apiDataArr = $this->chaoxing->get_schedule_list($schoolId);

         // 获取默认校区
         $campusParams['isDelete'] = 0;
         $campusParams['schoolId'] = $schoolId;
         $campusArr = $this->schoolModel->get_campus_list($campusParams);
         if($campusArr) {
             $defaultCampusId = $campusArr[0]['id'];
         } else {
             $defaultCampusId = 0;
         }

        // 获取本校课程表
        $scheduleParams['schoolId'] = $schoolId;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        $scheduleList = array_value_to_key($scheduleList, 'school_id,schedule_this_week');
        // 更新本周课表数据
        $this->__update_schedule_data($schoolId, $defaultCampusId, $scheduleList, $apiDataArr);
        
        // 重新获取本校课程表
        $scheduleParams['schoolId'] = $schoolId;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        $scheduleList = array_value_to_key($scheduleList, 'school_id,schedule_this_week');
        // 获取老师列表
        $teacherParams['schoolId'] = $schoolId;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'x_teacher_id');
        // 获取班级列表
        $classParams['schoolId'] = $schoolId;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'x_class_id');
        // 获取教室列表
        $roomParams['schoolId'] = $schoolId;
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'x_classroom_id');
        // 获取课表科目列表
        $scheduleLessonParams['schoolId'] = $schoolId;
        $scheduleLessonList = $this->classesModel->get_school_schedule_lesson_for_sync($scheduleLessonParams);
        $scheduleLessonList = array_value_to_key($scheduleLessonList, 'schedule_lesson_id');

        // 将全部数据设置为已删除状态
        $deleteState['is_delete'] = 1;
        $this->db->update(ClassesModel::$scheduleLessonTable, $deleteState, "`school_id`='{$schoolId}' AND `campus_id`='{$defaultCampusId}'");

        // 更新本周课表课程内容
        $this->__update_schedule_lesson_data($schoolId, $defaultCampusId, $scheduleList, $scheduleLessonList, $teacherList, $classList, $roomList, $apiDataArr);
    }
    // 课表接口，更新课程表数据
    private function __update_schedule_data($schoolId, $defaultCampusId, $scheduleList, $apiDataArr){
        $weekKey = $schoolId . 1;

        $thisWeekData['grade_id'] = 0;

        $thisWeekData['school_id'] = $schoolId;
        $thisWeekData['campus_id'] = $defaultCampusId;     // 设置校区ID
        $thisWeekData['schedule_title'] = $apiDataArr['semester'] ? $apiDataArr['semester'] : '';
        $thisWeekData['schedule_this_week'] = 1;
        // 获取时间点
        if($apiDataArr['timeSettings']) {
            $thisWeekData['schedule_week_days'] = $apiDataArr['timeSettings']['daysPerWeek'];
            $thisWeekData['schedule_morning_number'] = $apiDataArr['timeSettings']['morningLessons'];
            $thisWeekData['schedule_afternoon_number'] = $apiDataArr['timeSettings']['afternoonLessons'];
            $thisWeekData['schedule_early_morning_number'] = $apiDataArr['timeSettings']['earlyMorningLessons'];
            $thisWeekData['schedule_night_number'] = $apiDataArr['timeSettings']['nightLessons'];
            $thisWeekData['schedule_time_json'] = json_encode($apiDataArr['timeSettings']['times'], JSON_UNESCAPED_UNICODE);
        }
        $thisWeekData['updatetime'] = date("Y-m-d H:i:s");
        if(isset($scheduleList[$weekKey])) {
            // 保留原来的课前多少分钟考勤与是否重新考勤
            if($apiDataArr['timeSettings']) {
                $oldScheduleArr = json_decode($scheduleList[$weekKey]['schedule_time_json'], true);
                $newScheduleArr = json_decode($thisWeekData['schedule_time_json'], true);
                // echo '<pre>';var_export($oldScheduleArr);var_export($newScheduleArr);exit;
                if($oldScheduleArr) {
                    foreach($oldScheduleArr as $key => $value) {
                        if(isset($newScheduleArr[$key])) {
                            // 判断是否删除
                            if(isset($value['sign_interval'])) {
                                $newScheduleArr[$key]['sign_interval'] = $value['sign_interval'];
                            }
                            if(isset($value['refresh'])) {
                                $newScheduleArr[$key]['refresh'] = $value['refresh'];
                            }
                        }
                    }
                    $thisWeekData['schedule_time_json'] = json_encode($newScheduleArr, JSON_UNESCAPED_UNICODE);
                }
            }

            $this->db->update(ClassesModel::$scheduleTable, $thisWeekData, "id='{$scheduleList[$weekKey]['id']}'");
        } else {
            $thisWeekData['createtime'] = $thisWeekData['updatetime'];
            $this->db->insert(ClassesModel::$scheduleTable, $thisWeekData);
        }
    }
    // 课表接口，更新课程表课程数据
    private function __update_schedule_lesson_data($schoolId, $campusId, $scheduleList, $scheduleLessonList, $teacherList, $classList, $roomList, $scheduApiData){

        $insertLessonBatch = $updateLessonBatch = array();

        $scheduleKey = $schoolId . 1;
        $scheduleId = $scheduleList[$scheduleKey]['id'];
        if($scheduApiData) {
            // 遍历数据
            foreach($scheduApiData as $lesson){
                if(isset($classList[$lesson['qualifiedClassID']])) {
                    $lessonData['school_id'] = $schoolId;
                    $lessonData['campus_id'] = $campusId;       // 设置校区id
                    $lessonData['class_id'] = isset($classList[$lesson['qualifiedClassID']]) ? $classList[$lesson['qualifiedClassID']]['id'] : 0;
                    $lessonData['schedule_id'] = $scheduleId;
                    $lessonData['schedule_week_index'] = $lesson['weekDay'];
                    $lessonData['schedule_class_index'] = $lesson['timeslot'];
                    $lessonData['schedule_lesson_id'] = $scheduleId . '_' . $lessonData['class_id']. '_' . $lesson['weekDay']. '_' . $lesson['timeslot'];
                    $lessonData['schedule_lesson'] = $lesson['subjectName'];
                    $lessonData['is_delete'] = 0;
                    // 如果有授课老师
                    $lessonData['schedule_teacher'] = count($lesson['teachers']) && isset($teacherList[$lesson['teachers'][0]['teacherEID']]) ? $teacherList[$lesson['teachers'][0]['teacherEID']]['id'] : 0;
                    // 如果有课室
                    $lessonData['schedule_room_id'] = isset($roomList[$lesson['locationID']]) && $lesson['locationID'] ? $roomList[$lesson['locationID']]['id'] : 0;
                    $lessonData['updatetime'] = date("Y-m-d H:i:s");
                    if(isset($scheduleLessonList[$lessonData['schedule_lesson_id']])) {
                        $updateLessonBatch[] = $lessonData;
                    } else {
                        $lessonData['createtime'] = $lessonData['updatetime'];
                        $insertLessonBatch[] = $lessonData;
                    }
                }
            }
        }
        if(count($insertLessonBatch)) $this->db->insert_batch(ClassesModel::$scheduleLessonTable, $insertLessonBatch);
        if(count($updateLessonBatch)) $this->db->update_batch(ClassesModel::$scheduleLessonTable, $updateLessonBatch, "schedule_lesson_id");
    }

    // 提交数据到服务器
    private function send_post($url, $data = array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $tmpInfo = curl_exec($ch);

        if(curl_errno($ch)) return curl_error($ch);
        curl_close($ch);
        return $tmpInfo;
    }
}
